<?php
/**
 * skin_records 的 store_id与wechat_user_id 的数据同步到store_pivot_wechat_user 中
 */

namespace App\Services\DBHelpers;


use App\Models\Panx\SkinDetector;
use App\Models\Store\SkinRecord;
use App\Models\Store\StorePivotWechatUser;
use Illuminate\Support\Facades\DB;

class SkinRecordSyncStorePivotWechatUser
{

    /**
     * @deprecated- 线上已更新 2018-9-27 18:37:35
     *
     * \App\Services\DBHelpers\SkinRecordSyncStorePivotWechatUser::run()
     *
     * @throws \Exception
     */
    public static function run()
    {
        return "Don't run this";

        $skin_records = (new SkinRecord)->where([
            ['store_id', '<>', 0],
            ['wechat_user_id', '<>', 0]
        ])
            ->whereIn('skin_detector_id', SkinDetector::validatedIds())
            ->select(['store_id', 'wechat_user_id'])
            ->groupBy('wechat_user_id', 'store_id')
            ->get()
            ->toArray(); //->unique('wechat_user_id')->values()->toArray()

        $store_pivot_wechat_user = (new StorePivotWechatUser)->select(['store_id', 'wechat_user_id'])
            ->groupBy('wechat_user_id', 'store_id')
            ->get()
            ->toArray();

        $insert_data = self::assembleInsertData($skin_records, $store_pivot_wechat_user);

        DB::table('store_pivot_wechat_user')->insert($insert_data);

        logger(count($insert_data));
        return 'create ' . count($insert_data);
    }

    /**
     * @param $skin_records
     * @param $store_pivot_wechat_user
     * @return array
     */
    private static function assembleInsertData(array $skin_records, array $store_pivot_wechat_user): array
    {
        $insert_data = [];
        foreach ($skin_records as $record) {
            if (!in_array($record, $store_pivot_wechat_user)) {
                $insert_data[] = $record;
            }
        }
        return $insert_data;
    }

}